<template>
  <div class="main-container backend-management">
    <div class="container">
      <el-scrollbar>
        <el-menu
          class="backendManagerMenu"
          :default-active="menuActive"
          :default-openeds="['0', '4', '5']"
        >
          <div v-for="(item, index) in menuList" :key="index">
            <el-submenu v-if="item.hasChildren" :index="index.toString()">
              <template #title>
                <div class="item">
                  <!-- <svg-icon class-name="item-img" :icon-class="item.icon" /> -->
                  <img :src="isMenuActive(index.toString()) ? item.chooseSvgPicture : item.choosePicture" class="item-img" />
                  <span>{{ item.catalogName }}</span>
                </div>
              </template>
              <el-menu-item
                v-for="(val, idx) in item.children"
                :key="idx"
                @click="handleMenuItemClick(val, index, idx)"
                :index="index.toString() + '-' + idx"
              >
                <!-- {{ val.name }} -->
                <div class="item">
                  <!-- <svg-icon class-name="item-img" :icon-class="val.icon" /> -->
                  <img :src="isMenuActive(index.toString() + '-' + idx) ? val.chooseSvgPicture : val.choosePicture" class="item-img" />
                  <div>{{ val.catalogName }}</div>
                </div>
              </el-menu-item>
            </el-submenu>
            <el-menu-item
              v-else
              :index="index.toString()"
              @click="handleMenuItemClick(item, index, -1)"
            >
              <template #title>
                <!-- <el-icon v-if="item.icon">
                  <SvgIcon :name="item.icon!"></SvgIcon>
                </el-icon> -->
                <div class="item">
                  <!-- <svg-icon class-name="item-img" :icon-class="item.icon" /> -->
                  <img :src="isMenuActive(index.toString()) ? item.chooseSvgPicture : item.choosePicture" class="item-img" />
                  <span>{{ item.catalogName }}</span>
                </div>
                <!-- {{ item.name }} -->
              </template>
            </el-menu-item>
          </div>
        </el-menu>
      </el-scrollbar>
      <div class="content">
        <el-breadcrumb separator="/">
          <!--        <el-breadcrumb-item>后台管理</el-breadcrumb-item>-->
          <!--        <el-breadcrumb-item>数据资源管理</el-breadcrumb-item>-->
          <el-breadcrumb-item
            v-for="(item, index) in breadcrumbList"
            :key="index"
            >{{ item.name }}</el-breadcrumb-item
          >
        </el-breadcrumb>
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, getCurrentInstance } from 'vue'
import type { MenuTree, MenuItem } from '@/api/back-management/menu/interface'
// import { useCurrentUserStore } from '@/stores/current-user'
// import { Icon } from 'vue3-icon-picker'
import ElScrollbar from 'element-ui/lib/scrollbar'

const breadcrumbList = ref([
  {
    name: '后台管理',
  },
])

// interface MenuItem {
//   name: string;
//   icon?: string;
//   path?: string;
//   hasChildren: boolean;
//   children?: Array<MenuItem>;
// }

// const menuList = ref<Array<any>>([
//   {
//     name: '用户管理',
//     icon: 'user-management',
//     hasChildren: true,
//     children: [
//       {
//         name: '用户管理',
//         path: '/backend-management/user-management',
//         hasChildren: false,
//       },
//       {
//         name: '会话管理',
//         path: '/backend-management/session-management',
//         hasChildren: false,
//       },
//       {
//         name: '黑名单管理',
//         path: '/backend-management/blacklist-management',
//         hasChildren: false,
//       },
//     ],
//   },
//   {
//     name: '部门管理',
//     icon: 'dept-management',
//     path: '/backend-management/dept-management',
//     hasChildren: false,
//   },
//   {
//     name: '角色管理',
//     icon: 'role-management',
//     path: '/backend-management/role-management',
//     hasChildren: false,
//   },
//   {
//     name: '菜单管理',
//     icon: 'menu-management',
//     path: '/backend-management/menu-management',
//     hasChildren: false,
//   },
//   // {
//   //   name: '日志管理',
//   //   icon: 'log-management',
//   //   hasChildren: true,
//   //   children: [
//   //     {
//   //       name: '登录日志记录',
//   //       hasChildren: false,
//   //       path: '/backend-management/login-log-management',
//   //     },
//   //     {
//   //       name: '操作日志记录',
//   //       path: '/backend-management/action-log-management',
//   //       hasChildren: false,
//   //     },
//   //   ],
//   // },
//   {
//     name: '数据资源管理',
//     icon: 'data-management',
//     hasChildren: true,
//     children: [
//       {
//         name: '底图资源管理',
//         path: '/backend-management/base-map-resource',
//         hasChildren: false,
//       },
//       // {
//       //   name: '数据目录管理',
//       //   path: '/backend-management/data-catalog',
//       //   hasChildren: false,
//       // },
//     ],
//   },
// ])

const vm = getCurrentInstance()

const route = vm?.proxy?.$route
const router = vm?.proxy?.$router

const menuActive = ref('')
const currentPath = route?.path || ''
const { currentUser } = vm?.proxy?.$store.state.user

const getIcon = (key: string) => {
  let icon = ''
  switch (key) {
    case 'userManage':
      icon = 'user-management'
      break
    case 'menuManage':
      icon = 'dept-management'
      break
    case 'roleManage':
      icon = 'role-management'
      break
    case 'logsManage':
      icon = 'menu-management'
      break
    case 'dictManage':
      icon = 'data-management'
      break
  }
  return icon
}

const menuList = computed(() => {
  if (!currentUser?.moduleTree || !currentUser.moduleTree[0]?.children) {
    return []
  }
  
  const treeData = currentUser.moduleTree[0].children.filter(
    (i: MenuTree) => i.code === 'systemManage'
  ) as MenuTree[]
  
  if (!treeData[0]?.children) {
    return []
  }
  
  const menus = treeData[0].children
  
  menus.forEach((menu: any) => {
    menu.icon = getIcon(menu.code || '')
    menu.name = menu.catalogName // 添加name属性
    if (menu.children) {
      menu.children.forEach((child: any) => {
        child.icon = getIcon(child.code || '')
        child.name = child.catalogName // 添加name属性
      })
    }
  })

  // console.log(menus, 'menus')
  return menus || []
})

// 判断菜单是否被选中
const isMenuActive = (menuIndex: string) => {
  return menuActive.value === menuIndex
}

// 初始化菜单选中状态
const initMenuActive = () => {
  let found = false
  
  // 遍历菜单，查找匹配当前路由的菜单项
  menuList.value.forEach((val: any, index: number) => {
    if (val.routePath === currentPath) {
      menuActive.value = index.toString()
      breadcrumbList.value = [{ name: '后台管理' }, { name: val.catalogName || '' }]
      found = true
      return
    }
    if (val.hasChildren && val.children) {
      val.children.forEach((info: any, idx: number) => {
        if (info.routePath === currentPath) {
          menuActive.value = index + '-' + idx
          breadcrumbList.value = [{ name: '后台管理' }, { name: val.catalogName || '' }, { name: info.catalogName || '' }]
          found = true
          return
        }
      })
    }
  })
  
  // 如果没有找到匹配的菜单项，且当前路径是根路径，则默认选中第一个菜单项
  if (!found && (currentPath === '/backend-management' || currentPath === '/backend-management/')) {
    if (menuList.value.length > 0) {
      const firstMenu: any = menuList.value[0]
      if (firstMenu.hasChildren && firstMenu.children && firstMenu.children.length > 0) {
        // 如果第一个菜单有子菜单，选中第一个子菜单
        menuActive.value = '0-0'
        breadcrumbList.value = [
          { name: '后台管理' },
          { name: firstMenu.catalogName || '' },
          { name: firstMenu.children[0].catalogName || '' }
        ]
        // 跳转到第一个子菜单的路径
        if (firstMenu.children[0].routePath && router) {
          router.replace(firstMenu.children[0].routePath)
        }
      } else {
        // 如果第一个菜单没有子菜单，直接选中第一个菜单
        menuActive.value = '0'
        breadcrumbList.value = [{ name: '后台管理' }, { name: firstMenu.catalogName || '' }]
        // 跳转到第一个菜单的路径
        if (firstMenu.routePath && router) {
          router.replace(firstMenu.routePath)
        }
      }
    }
  }
}

// 监听菜单数据变化，当菜单数据加载完成后初始化选中状态
if (vm?.proxy) {
  vm.proxy.$watch('menuList', () => {
    if (menuList.value.length > 0) {
      initMenuActive()
    }
  }, { immediate: true })
}

// 立即执行一次初始化
initMenuActive()

const handleMenuItemClick = (item: any, index: number, idx: number) => {
  const name = item.catalogName || item.name || ''
  menuActive.value = idx === -1 ? `${index}` : `${index}-${idx}`
  breadcrumbList.value.length = 1
  breadcrumbList.value.push({
    name,
  })
  const path = item.routePath
  if (path && router) {
    router.push(path)
  } else if (router) {
    router.push('/backend-management')
  }
}
</script>

<style lang="scss" scoped>
.main-container {
  height: 100%;

  :deep(.query-content) {
    padding-left: 20px;
    width: 100%;
    line-height: 62px;
    border-bottom: 1px solid #eeeff5;
    margin-bottom: 20px;

    .el-form {
      height: 80px;
      align-items: center;
      display: flex;
      &-item {
        display: flex;
        align-items: center;
        height: 40px;

        .el-form-item__content {
          display: flex;
          align-items: center;
        }

        .el-button {
          padding-bottom: 0;
          padding-top: 0;
          line-height: 100%;
        }
      }
    }
  }

  :deep(.base-map-resource-content) {
    .query-content {
      box-sizing: border-box;
    }

    .table {
      box-sizing: border-box;
    }
    .el-pagination {
      display: flex;
    }
  }
}
.backendManagerMenu {
  width: 256px;
  height: 100%;

  :deep(.svg-icon) {
    svg {
      width: 16px;
      height: 16px;
      color: #adb8ca;
    }
  }

  :deep(.is-active) {
    .el-sub-menu__title {
      color: #409EFF !important;
    }

    .svg-icon {
      svg {
        color: #409EFF !important;
      }
    }
  }

  :deep(.el-menu-item) {
    height: 60px;
    line-height: 60px;
    display: flex;
    align-items: center;
    box-sizing: border-box;
    
    .item {
      height: 100% !important;
      line-height: 1 !important;
    }
    
    &.is-active {
      background: #ecf5ff !important;
      color: #409EFF !important;
      border-radius: 4px;
      
      .svg-icon {
        svg {
          color: #409EFF !important;
        }
      }
    }
  }

  .item {
    display: flex;
    align-items: center;
    height: 100%;
    line-height: 1;
    box-sizing: border-box;

    &-img {
      width: 20px;
      height: 20px;
      margin-right: 5px;
      flex-shrink: 0;
    }

    &-icon {
      height: 20px;
      width: 20px;
      margin-right: 5px;
      flex-shrink: 0;
    }

    span, div {
      line-height: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

:deep(.el-sub-menu) {
  .el-menu-item {
    padding-left: 47px !important;
    height: 60px;
    line-height: 60px;
    display: flex;
    align-items: center;
    
    .item {
      height: 100% !important;
      line-height: 1 !important;
    }
    
    &.is-active {
      background: #ecf5ff !important;
      color: #409EFF !important;
      border-radius: 4px;
      margin: 0 8px;
      
      .svg-icon {
        svg {
          color: #409EFF !important;
        }
      }
    }
  }
}

.container {
  width: 100%;
  height: 100%;
  display: flex;

  :deep(.el-scrollbar) {
    .el-scrollbar__wrap {
      .el-scrollbar__view {
        height: 100%;

        .el-menu {
          border-right: none;
        }
      }
    }
  }

  :deep(.backend-form) {
    position: relative;
    .backend-button {
      position: absolute;
      right: 16px;
    }
  }

  .content {
    box-sizing: border-box;
    width: calc(100% - 256px);
    height: 100%;
    background-color: #f0f4f9;
    padding: 14px 20px 20px 20px;

    :deep(.el-breadcrumb) {
      margin-bottom: 13px;
    }
  }

  :deep(.el-submenu__title) {
    height: 60px;
    line-height: 60px;
    display: flex;
    align-items: center;

    .item {
      height: 100% !important;
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 700;
      line-height: 1 !important;
    }
  }

  :deep(.el-menu) {
    > div > .el-menu-item {
      height: 60px;
      line-height: 60px;
      display: flex;
      align-items: center;

      .item {
        height: 100% !important;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 700;
        line-height: 1 !important;
      }
    }
  }
}
</style>
<style lang="scss">
.outline-dialog {
  //width: 462px;
  //background: #ffffff;
  //border-radius: 4px;

  .el-dialog__body {
    //padding-bottom: 0 !important;
  }

  .el-dialog__footer {
    padding-top: 30px !important;
    border-top: 1px solid #e5e5e5;
  }

  .el-dialog__header {
    border-bottom: 1px solid #e5e5e5;

    .el-dialog__title {
      width: 64px;
      height: 16px;
      font-size: 16px;
      font-weight: bold;
      color: #27475f;
    }
  }

  .dialog-footer {
    width: 100%;
    height: 100%;
    text-align: center;
  }
}
</style>
